package com.mibsvc.appsvc.util;

import lombok.Data;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.data.domain.Persistable;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static javax.persistence.GenerationType.IDENTITY;

/**
 * @author Litar
 */
@Data
@MappedSuperclass
public abstract class Model implements Persistable<String> {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    @Column(length = 32)
    private String id;

    @Column(columnDefinition = "varchar(32) comment \"操作人\"")
    private String opBy;

    @Column(columnDefinition = "int(32) comment \"操作时间\"")
    private Integer opAt;

    @Column(columnDefinition = "boolean comment \"删除标记\"")
    private Boolean isDel;

    @Column(columnDefinition = "varchar(32) comment \"创建人\"")
    private String crBy;

    @Column(columnDefinition = "int(32) comment \"创建时间\"")
    private Integer crAt;

    final public Map<String, Object> ToMap() {

        Map<String, Object> map = new HashMap(0);
        try {
            Field[] fields = this.getClass().getDeclaredFields();
            for (Field field : fields) {
                map.put(field.getName(), field.get(this));
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return map;
    }

    public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
        if (map == null) {
            return null;
        }

        Object obj = beanClass.newInstance();

        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            int mod = field.getModifiers();
            if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                continue;
            }

            field.setAccessible(true);
            field.set(obj, map.get(field.getName()));
        }

        return obj;
    }
    @Override
    public boolean isNew() {
        return false;
    }

}
